<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j page-select-decorate">
    <!-- 商家 start -->
    <new-index
      v-if="setTopHeader === 'shops'"
      :decorate-page-index="decoratePageIndex"
      :decorate-header="getHeaderData"
      :category-list="categoryList"
      :is-collection="isCollection"
      :operation-type="'store'"
      :shop-info="shopInfo"
    />
    <!-- 商家 end -->

    <!-- 平台 start -->
    <commonHeaders
      v-if="setTopHeader === 'platform'"
      :other-header="decorateHeader"
    />
    <template v-if="decoratePageIndex.length > 0">
      <new-index
        v-if="setTopHeader !== 'shops'"
        :decorate-page-index="decoratePageIndex"
      />
    </template>
    <!-- 平台 end -->
  </div>
</template>
<script setup>
import commonHeaders from '@/components/decorate-component/common-header/index.vue' // 平台头部
import qs from 'qs'

const decorateHeader = ref([]) // 商家头部
const setTopHeader = computed(() => { // 判断当前显示商家导航还是平台导航
  let types = ''
  if (decorateHeader.value.length > 0) {
    if ('storeStyle' in decorateHeader.value[0].dataField) {
      types = 'shops'
    } else {
      types = 'platform'
    }
  } else {
    types = 'none'
  }
  return types
})
const getHeaderData = computed(() => {
  const arr = []
  arr.push(decorateHeader.value[0].dataField)
  return arr
})

const $route = useRoute()
const decoratePageIndex = ref([])

// 获取装修配置信息
const shopId = ref(null)
const getDecorateData = (renovationIdVal) => {
  return new Promise((resolve) => {
    http({
      url: '/shopRenovation/homepage',
      method: 'get',
      params: {
        renovationType: 1,
        renovationId: renovationIdVal
      }
    }).then(({ data }) => {
      if (data === '' || data == null) {
        decoratePageIndex.value = []
        decorateHeader.value = []
      } else {
        if ($route.path === '/select-decorate') {
          document.title = data.name
        }
        decoratePageIndex.value = []
        decorateHeader.value = []
        shopId.value = data.shopId
        if (data && data.content) {
          if (Array.isArray(JSON.parse(data.content))) {
            JSON.parse(data.content).forEach(element => {
              if (element.type === 'shop_signs') {
                decorateHeader.value.push(element)
              } else {
                decoratePageIndex.value.push(element)
              }
            })
            resolve(true)
          }
        }
      }
    }).catch(() => {
      decoratePageIndex.value = []
    })
  })
}

// 匹配商品
const matchproducts = async (arr = []) => {
  const res = await searchGoodsMessage(arr || []) // 根据现有的id查询所有的商品信息
  const stores = await searchStoreMessage(arr || []) // 根据现有的店铺id查询所有的店铺信息
  arr.forEach(item => {
    if (item.type === 'goods_list') { // 商品列表
      item.dataField.goodsList = handleScreenGoods(item.dataField.goodsList, res, 'id')
    } else if (item.type === 'discount_coupon') { //  优惠团购
      const discountPramas = {
        // 商品名称
        prodType: 'prodType', // 商品类型
        status: 'status', // 商品状态
        price: 'activityPrice', // 商品价格
        imgs: 'pic', // 商品图片
        description: 'brief', // 商品描述
        activityStatus: 'activityStatus'
      }
      item.dataField.goodsList = handleScreenGoods(item.dataField.goodsList, res, 'id', discountPramas)
    } else if (item.type === 'limited_skill') { // 秒杀商品
      const limitePramas = {
        // 商品名称
        prodType: 'prodType', // 商品类型
        status: 'status', // 商品状态
        price: 'activityPrice', // 商品价格
        imgs: 'pic', // 商品图片
        description: 'brief', // 商品描述
        activityStatus: 'activityStatus'
      }
      item.dataField.goodsList = handleScreenGoods(item.dataField.goodsList, res, 'prodId', limitePramas)
    } else if (item.type === 'goods_module1') { // 商品模块1
      item.dataField.leftConfig.goodsList = handleScreenGoods(item.dataField.leftConfig.goodsList, res, 'id')
      item.dataField.centerConfig.goodsList = handleScreenGoods(item.dataField.centerConfig.goodsList, res, 'id')
      item.dataField.rightConfig.goodsList = handleScreenGoods(item.dataField.rightConfig.goodsList, res, 'id')
    } else if (item.type === 'goods_module2') { // 商品模块2
      item.dataField.maingoodsList = handleScreenGoods(item.dataField.maingoodsList, res, 'id')
      item.dataField.othergoodsList = handleScreenGoods(item.dataField.othergoodsList, res, 'id')
    } else if (item.type === 'goods_module3') { // 商品模块3
      item.dataField.leftConfig.goodsList = handleScreenGoods(item.dataField.leftConfig.goodsList, res, 'id')
      item.dataField.rightConfig.goodsList = handleScreenGoods(item.dataField.rightConfig.goodsList, res, 'id')
    } else if (item.type === 'goods_module4' || item.type === 'goods_module5') { // 商品模块4
      item.dataField.goodsList = handleScreenGoods(item.dataField.goodsList, res, 'id')
    } else if (item.type === 'store_list') { // 店铺列表
      item.dataField.storeList = handleScreenStrore(item.dataField.storeList, stores)
    }
  })
  return arr
}

watch(() => $route, async (newVal) => {
  if (newVal.path == '/select-decorate') {
    const query = newVal.query
    if (query.renovationId) {
      await getDecorateData(query.renovationId)
      decoratePageIndex.value = matchproducts(decoratePageIndex.value)
      selectAllInterface()
    }
  }
}, { deep: true })

onMounted(async () => {
  // 筛选商品和店铺
  const query = $route.query
  await getDecorateData(query.renovationId)
  await matchproducts(decoratePageIndex.value)
  selectAllInterface()
})

// 查询商品信息
const searchGoodsMessage = (arr) => {
  let goodsArr = []
  arr.forEach(item => {
    if (item.type === 'limited_skill') { // 秒杀商品
      item.dataField.goodsList.forEach(v => {
        goodsArr.push(v.prodId)
      })
    } else if (item.type === 'discount_coupon') { // 优惠团购
      item.dataField.goodsList.forEach(v => {
        goodsArr.push(v.id)
      })
    } else if (item.type === 'goods_list') { // 商品信息
      item.dataField.goodsList.forEach(v => {
        goodsArr.push(v.id)
      })
    } else if (item.type === 'goods_module1') { // 商品模块1
      item.dataField.leftConfig && item.dataField.leftConfig.goodsList.forEach(v => {
        goodsArr.push(v.id)
      })
      item.dataField.centerConfig && item.dataField.centerConfig.goodsList.forEach(v => {
        goodsArr.push(v.id)
      })
      item.dataField.rightConfig && item.dataField.rightConfig.goodsList.forEach(v => {
        goodsArr.push(v.id)
      })
    } else if (item.type === 'goods_module2') { // 商品模块2
      item.dataField.maingoodsList && item.dataField.maingoodsList.forEach(v => {
        goodsArr.push(v.id)
      })
      item.dataField.othergoodsList && item.dataField.othergoodsList.forEach(v => {
        goodsArr.push(v.id)
      })
    } else if (item.type === 'goods_module3') { // 商品模块3
      item.dataField.leftConfig && item.dataField.leftConfig.goodsList.forEach(v => {
        goodsArr.push(v.id)
      })
      item.dataField.rightConfig && item.dataField.rightConfig.goodsList.forEach(v => {
        goodsArr.push(v.id)
      })
    } else if (item.type === 'goods_module4') { // 商品模块4
      item.dataField.goodsList && item.dataField.goodsList.forEach(v => {
        goodsArr.push(v.id)
      })
    } else if (item.type === 'goods_module5') { // 商品模块5
      item.dataField.goodsList && item.dataField.goodsList.forEach(v => {
        goodsArr.push(v.id)
      })
    }
  })
  goodsArr = Array.from(new Set(goodsArr))
  return new Promise((resolve) => {
    http({
      method: 'get',
      url: '/search/renovationPage',
      params: {
        prodIds: goodsArr,
        current: 1,
        size: goodsArr.length,
        getDelete: true
      },
      paramsSerializer: params => {
        return qs.stringify(params, { indices: false })
      }
    }).then(res => {
      resolve(res.data.records)
    })
  })
}
// 查询店铺信息
const searchStoreMessage = (arr) => {
  let storeArr = []
  arr.forEach(item => {
    if (item.type === 'store_list') {
      item.dataField.storeList.forEach(v => {
        storeArr.push(v.shopId)
      })
    }
  })
  storeArr = Array.from(new Set(storeArr))
  return new Promise((resolve) => {
    http({
      method: 'get',
      url: '/shop/listRenovationShop',
      params: {
        shopIds: storeArr
      },
      paramsSerializer: params => {
        return qs.stringify(params, { indices: false })
      }
    }).then(res => {
      resolve(res.data)
    })
  })
}
// 筛选商品回显 currentArr: 表示当前装修的商品，backReturnArr: 表示根据现有id查询后端返回的商品
const handleScreenGoods = (currentArr, backReturnArr, type, otherParams) => {
  let params = {}
  if (otherParams) {
    params = {
      ...otherParams
    }
  } else {
    params = {
      // 商品名称
      prodType: 'prodType', // 商品类型
      status: 'status', // 商品状态
      price: 'price', // 商品价格
      imgs: 'pic', // 商品图片
      description: 'brief', // 商品描述
      activityStatus: 'activityStatus'
    }
  }
  const arr = []
  for (let i = 0; i < currentArr.length; i++) {
    for (let j = 0; j < backReturnArr.length; j++) {
      if (currentArr[i][type] === backReturnArr[j].prodId) {
        for (const key in params) {
          currentArr[i][key] = backReturnArr[j][params[key]]
        }
        if (currentArr[i].price == null) {
          currentArr[i].price = backReturnArr[j].price
        }
        if (currentArr[i].orignPrice) {
          currentArr[i].orignPrice = backReturnArr[j].oriPrice
        }
        arr.push(currentArr[i])
      }
    }
  }
  return arr
}
// 筛选店铺信息
const handleScreenStrore = (currentArr, backReturnArr) => {
  const storeParams = {
    shopLogo: 'shopLogo',
    imgs: 'shopLogo',
    shopName: 'shopName',
    shopStatus: 'shopStatus',
    type: 'type',
    fansCount: 'fansCount',
    shopFocusNumber: 'fansCount'
  }
  const arr = []
  for (let i = 0; i < currentArr.length; i++) {
    for (let j = 0; j < backReturnArr.length; j++) {
      if (currentArr[i].shopId === backReturnArr[j].shopId) {
        for (const key in storeParams) {
          currentArr[i][key] = backReturnArr[j][storeParams[key]]
        }
        arr.push(currentArr[i])
      }
    }
  }
  return arr
}

// 获取店铺分类
const categoryList = ref([]) // 分类
const getCategoryMessage = () => {
  http({
    url: '/category/categoryInfo',
    method: 'get',
    params: {
      shopId: shopId.value,
      parentId: 0
    }
  }).then(res => {
    categoryList.value = res.data.categoryInfo
  })
}
/**
 * 获取用户是否收藏此店铺
 */
const isCollection = ref(false)
const getUserCollection = () => {
  http
    .get('/p/shop/collection/isCollection', {
      params: {
        shopId: shopId.value
      }
    })
    .then(({ data }) => {
      isCollection.value = data
    })
}
// 获取店铺信息
const shopInfo = ref({}) // 店铺信息
const getShopInfo = () => {
  http({
    url: '/shop/headInfo',
    method: 'get',
    params: {
      shopId: shopId.value
    }
  }).then(res => {
    shopInfo.value = res.data
  })
}
// 调用需要的接口
const selectAllInterface = () => {
  // 如果是商家装修页，此时需要获取分类
  if (setTopHeader.value === 'shops') {
    getCategoryMessage()
    getUserCollection()
    getShopInfo()
  }
}

</script>
<style lang="scss" scoped>
.page-select-decorate {
  min-height: calc(100vh - 268px);
  :deep(.select-decorate) {
    width: 100%;
    background: #f9f9f9
  }
  :deep(.empty .action .btn-r) {
    display: inline-block;
    padding: 6px 18px;
    border: 1px solid #ddd;
    background: #f9f9f9;
    border-radius: 30px;
    margin-top: 20px;
    margin-left: 10px;
    color: #666;
  }
}
</style>
